import fs from "fs-extra";
import ora from "ora";
import path from "path";
import shell from "shelljs";
const appDir = fs.realpathSync(process.cwd());
const resolveApp = (relativePath) => {
  return path.resolve(appDir, relativePath);
};
//删除文件夹

export async function removeDir(dir) {
  const spinner = ora("正在删除文件夹");
  spinner.start();
  try {
    await fs.remove(resolveApp(dir));
    spinner.succeed("删除成功");
  } catch (e) {
    spinner.fail("删除失败");
    return;
  }
}
export async function changPackageJson(name, info) {
  const pkg = await fs.readJson(resolveApp(`${name}/package.json`));

  Object.keys(info).forEach((item) => {
    if (item === "name") {
      pkg[item] = info[item] && info[item].trim() ? info[item].trim() : name;
    } else if (item === "keywords" && info[item] && info[item].trim()) {
      pkg[item] = info[item].split(",");
    } else if (info[item] && info[item].trim()) {
      pkg[item] = info[item];
    }
  });
  await fs.writeJson(resolveApp(`${name}/package.json`), pkg, { spaces: 2 });
  console.log("pkg", pkg);
  // pkg.name = info.name;
  // pkg.version = info.version;
  // pkg.description = info.description;
}

export function npmInstall(dir) {
  const spinner = ora("正在安装依赖....").start();
  if (shell.exec(`cd ${shell.pwd()}/${dir} && cnpm install --force -d`) !== 0) {
    console.log("安装失败，请手动安装");
    shell.exit(1);
  }
  spinner.succeed("安装成功");
  shell.exit(1);
}
